<template>
  <div class="page-container">
    <!-- <TemperatureChart 
    :config="configAll" 
    v-if="configAll"
    :data="tempData"
    :size="1"
     /> -->

    <!-- :config="configAll"  -->
    <TemperatureChart
      v-if="configXml && tempData"
      :data="tempData"
      :config="configXml"
      :parsedSetting="parsedSetting"
      :footerConfig="footerConfig"
      :noHandle="noHandle"
      :size="1"
      :scale="1"
      unit="mm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

import TemperatureChart from "./TemperatureChart.vue";

import { getConfigData, getTemperatureData } from "./tempertureApi.js";

import DesignUtils from "./DesignUtils";

import ParseXML from "./parseXML";
import parseStringToXml from "./parseStringToXml";


import { XmlParser } from "./utils/xmlUtil.ts"

import moment from "moment";

// import vitalSignText from "./vitalsign.ts";

import Custom_Variable from "./CUSTOM";

import { Base64 } from "js-base64";

let parseXML = new ParseXML();

let configAll = ref();
let dataList = ref([]);
let tempData = ref();
let configXml = ref();
let parsedSetting = ref();

// 不同处理点击事件的数据
let noHandle = ref([
  "日期",
  "表顶注释",
  "表底注释",
  "不升",
  "住院天数",
  "术后天数",
]);

let footerConfig = ref({
  currentWeek: 1,
  totalWeeks: 2,
});

/**
 * @method 解析出体温单的配置数据
 */
let parseTempConfig = (configJson: any) => {
  let { config: configXml, data: dataJson, ...other } = configJson;

  console.log("11111111111", configJson);

  const designUtils = new DesignUtils({ configJson, ...other });

  // 体温单线条/字体/图标/绘制规则等配置信息
  const config = {
    vitalLineOutToConfig: designUtils.getVitalLineOutToConfig(),
    vitalLineOverlapToConfig: designUtils.getVitalLineOverlapToConfig(),
    vitalTextOutToConfig: designUtils.getVitalTextOutToConfig(),
    vitalLineBlockToConfig: designUtils.getVitalLineBlockToConfig(),
    vitalRegionFillToConfig: designUtils.getVitalRegionFillToConfig(),
    vitalShowToConfig: designUtils.getVitalShowToConfig(),
    fontIdToStyle: designUtils.getFontIdToStyle(),
    linePenIdToStyle: designUtils.getLineIdToStyle(),
    symbolIdToStyle: designUtils.getSymbolIdToStyle(),
  };

  // 体温单底板设置数据
  const designData = {
    vitalLines: designUtils.getVitalLines(),
    vitalTexts: designUtils.getVitalTexts(),
  };

  const showSize = designUtils.getShowSize();
  const keyToNumber = designUtils.getKeyToNumber();
  const showRect = designUtils.getRectSize();

  let items = dataJson || [];

  items = resetItems(items, config);

  // 体温单显示数据
  const showData = {
    items: items,
    vitalTextOuts: designUtils.getVitalTextOuts(),
  };

  return { config, designData, showData, showSize, showRect, keyToNumber };
};

/**
 * @method 将数据解析成所需格式
 * @param items
 * @param config
 */
const resetItems = (items: any, config: any) => {
  // const {splitNumber, beginDate} = temperatureConfigData;

  let splitNumber = 4;
  let beginDate = "2025-07-31 00:00:00";

  let newItems = [];
  // 时间拆分配置 splitType：1时间点不拆分小格 2全局均分，精确到分显示 3时间点拆分成小格
  let vitalShowToConfig = config.vitalShowToConfig || {};
  let splitType = (vitalShowToConfig["时间"] || {}).splitType;
  let disScale;
  let splitBeginNumber = 0;

  for (let i = 0; i < items.length; i++) {
    let {
      name,
      index,
      innerIndex,
      value,
      otherValue,
      customName,
      date,
      flag,
      subArray,
      ...other
    } = items[i];
    let disIndex = 0;
    if (splitType && innerIndex < 5 && splitType != 2) {
      if (splitType == 3) {
        splitBeginNumber = 2;
      }
      disIndex = (innerIndex - splitBeginNumber) / splitNumber;
    }
    if (splitType == 2) {
      // 总共显示7天， 计算当前时间到开始时间
      let totalTimes = 7 * 24 * 60 * 60 * 1000;
      let disTimes = moment(date) - moment(beginDate);
      disScale = disTimes / totalTimes;
    }
    let threeValue = null;
    let beforeValue = null;
    let afterValue = null;
    let specialShow = false;
    // 大便次数特殊处理， 如果出现-4/N则去掉前面的-号
    // 显示格式：flag:2 N-n/E； flag:1 Nn/E
    if (name === "大便次数") {
      let config = parseShitValue(value, flag);
      beforeValue = config.beforeValue;
      afterValue = config.afterValue;
      specialShow = config.specialShow;
      threeValue = Custom_Variable.isEnema ? config.threeValue : null;

      if (subArray) {
        subArray = subArray.map((item: any) => {
          return {
            ...item,
            ...parseShitValue(item.value, item.flag),
            flag: null,
          };
        });
      }
      flag = null;
    }

    // 呼吸特殊处理， flag为1时，添加呼吸机，显示值R
    let showName = name.replace("UP", "").replace("DOWN", "");
    let cacheName = showName;
    /**
     * 下列部分需要修改
     */
    // if(showName==='呼吸' && flag==1){
    //   newItems.push({
    //     '_attr': {
    //       vitalsigns: '呼吸机',
    //       vitalsignsvalues: 'R',
    //       cellindex: index + disIndex,
    //       date: date,
    //       disScale: disScale, //显示位置在整个体温单中所占比列
    //       subItem: subArray?subArray.map(item=>{
    //         return {
    //           ...item,
    //           value: item.flag==1?'R': item.value,
    //         }
    //       }): subArray,
    //       flag: null,
    //     }
    //   });
    //   showName = `${showName}DOWN`;
    // }

    newItems.push({
      _attr: {
        vitalsigns: flag == 1 ? showName : name,
        vitalsignsvalues: value,
        vitalsignsoriginalvalues: otherValue,
        cellindex: index + disIndex,
        mainName: customName,
        date: date,
        flag: customName ? 0 : cacheName == "呼吸" ? "" : flag, // 该flag定义颜色
        isCus: customName ? true : false, // 如果是自定义项才取该标识，表示是否是录入的自定项
        subItem: subArray,
        ...other,
        disScale: disScale, //显示位置在整个体温单中所占比列
        beforeValue: beforeValue, // 大便灌肠的第一个输入框
        afterValue: afterValue, // 大便灌肠的第二个输入框
        specialShow: specialShow,
        threeValue: threeValue, // 大便灌肠的第三个输入框
      },
    });
  }

  // 配置了脉搏短绌则解析数据
  if (
    config.vitalRegionFillToConfig &&
    config.vitalRegionFillToConfig["脉搏短绌"]
  ) {
    let mbdcPoints = getMbdcPoints(newItems);
    newItems = newItems.concat(mbdcPoints);
  }

  return newItems;
};

/**
 * 解析大便值
 */
let parseShitValue = (value: any, flag: any) => {
  let beforeValue, afterValue, specialShow, threeValue;
  if (`${value}`.indexOf("/") > -1) {
    let valueArray = (value.split("/")[0] || "").split("-");
    if (Custom_Variable.isEnema)
      threeValue = (value.split("/")[1] || "").replace("E", "");
    // 解析一下数据
    if (`${value}`.substring(0, 1) === "-") {
      value = `${value}`.substring(1, `${value}`.length);
    }
    if (flag == 2) {
      if (valueArray.length === 2) {
        beforeValue = valueArray[0];
        afterValue = valueArray[1];
        specialShow = true;
      } else if (valueArray.length === 1) {
        afterValue = valueArray[0];
        specialShow = true;
      }
    }
  }
  return {
    threeValue: threeValue || "",
    beforeValue,
    afterValue,
    specialShow,
  };
};

let getMbdcPoints = (items: any) => {
  // 解析生成脉搏短促数据， 同一时间内，脉搏小于心率
  let mbdcPoints = [];
  let mbdc = [];
  let xlPoints = items.filter((v) => v["_attr"].vitalsigns === "心率");
  let mbPoints = items.filter((v) => v["_attr"].vitalsigns === "脉搏");
  let indexSub = 0;

  let indexs = Array.from(
    new Set(
      xlPoints
        .map((v) => v["_attr"].cellindex)
        .concat(mbPoints.map((v) => v["_attr"].cellindex))
    )
  );
  indexs.sort((a, b) => a - b);

  for (let i = 0; i < indexs.length; i++) {
    let index = indexs[i];
    let xlPoint = xlPoints.find((v) => v["_attr"].cellindex === index);
    // index, innerIndex
    let mbPoint = mbPoints.find((v) => v["_attr"].cellindex === index);

    if (
      xlPoint &&
      mbPoint &&
      xlPoint["_attr"].vitalsignsvalues &&
      mbPoint["_attr"].vitalsignsvalues &&
      mbPoint["_attr"].vitalsignsvalues < xlPoint["_attr"].vitalsignsvalues
    ) {
      if (!mbdc[indexSub]) {
        mbdc[indexSub] = [];
      }
      mbdc[indexSub].push(mbPoint);
      mbdc[indexSub].unshift(xlPoint);
    } else {
      indexSub++;
      continue;
    }
  }

  mbdc = mbdc.filter((v) => !!v);

  for (let i = 0; i < mbdc.length; i++) {
    mbdc[i] = mbdc[i].map((v) => {
      return {
        _attr: {
          ...v["_attr"],
          vitalsigns: "脉搏短绌",
          groupName: `脉搏短绌${i}`,
        },
      };
    });
    mbdcPoints = mbdcPoints.concat(mbdc[i]);
  }

  return mbdcPoints;
};

/**
 * 每周第一天第一列显示历史药物过敏
 * @param props
 */
let parseShowTcAllergy = async (props: any, dataSource: any, week: any) => {
  props = props || {};
  const { patient } = props;

  // 查找第一次出现的药物过敏
  let allergy = dataSource.find((v) => {
    return v.name === "药物过敏" && v.index === 0;
  });

  // 获取日期
  let beginDate = week[0];
  let tcAllergyList = this.state.tcAllergyList || [];

  // 根据时间过滤
  tcAllergyList = tcAllergyList.filter(
    (v) => moment(v.recordDate).valueOf() < moment(week[0]).valueOf()
  );

  let subArray = tcAllergyList.map((v, i) => {
    return {
      index: i,
      value: v.allergicDrugs,
      date: v.recordDate,
    };
  });

  if (allergy) {
    if (allergy.subArray) {
      allergy.subArray = subArray.concat(subArray.subArray);
    } else {
      allergy.subArray = subArray.concat([
        { index: 0, value: allergy.value, date: allergy.date },
      ]);
    }
  } else {
    dataSource.push({
      name: "药物过敏",
      index: 0,
      subArray: subArray,
    });
  }

  return dataSource;
};

let obtainTempSetting = async () => {
  getConfigData().then((res: any) => {
    let vitalSignText = res.data;

    // let content = Base64.decode(vitalSignText.body.content);

    // vitalSignText.body.content = content

    

    const { xmlDoc } = parseStringToXml(vitalSignText.body.content);
    

    const parser = new XmlParser(vitalSignText.body.content);
			let parsedXmlData = parser.parse();

      parsedSetting.value = parsedXmlData;

			console.log("11111parsedData",parsedXmlData);


    console.log("44444444",xmlDoc);

    // let configXml = xmlDoc;

    configXml.value = xmlDoc;

    // let configJson = parseXML.xmlToJson(configXml);
    // if (!configJson["vitalsign"]) {
    //   console.log("11111", "配置错误");
    //   return;
    // } else {
    //   console.log("11111", "配置正确");
    // }

    // obtainTempData(configJson);
  });
};

let obtainTempData = async () => {
  getTemperatureData().then(async (res: any) => {
    console.log("体温表数据", res);
    dataList.value = res.data.body;

    let data = res.data.body || [];

    // debugger
    if (Custom_Variable.customItemUnitShow && !!data.length) {
      data.forEach((item: any) => {
        if (item["name"].includes("自定义项")) {
          item.customName += "(ml)"; // 自定义项特殊处理
        }
      });
    }

    // if (Custom_Variable.displayHistoryOfAllergicDrugs) {
    //   data = await parseShowTcAllergy(props, data, week);
    // }

    tempData.value = data;

    // configJson.data = data;

    // configAll.value = parseTempConfig(configJson);

    // // beginDate={this.props.beginDate}
    // configAll.value.beginDate = "2025-08-28";
    // configAll.value.unit = "mm"; // 单位， mm/cm/px等
    // configAll.value.scale = 1; // 缩放比例
    // configAll.value.split = true; // 一个格子是否拆分成多个小格，默认拆分
    // configAll.value.splitNumber = 4; // 拆分成多少个小格， 默认4
    // configAll.value.splitBeginNumber = 0; // index开始值， 默认0

    // configAll.value.noHandle = [
    //   "日期",
    //   "表顶注释",
    //   "表底注释",
    //   "不升",
    //   "住院天数",
    //   "术后天数",
    // ]; // 不同处理点击事件的数据

    // configAll.value.hideTemp = false; // 隐藏物理降温按钮

    // configAll.value.hideEdit = false; // 隐藏编辑按钮

    // configAll.value.hideRemove = false; // 隐藏删除按钮
    // configAll.value.showResize = true; // 默认显示缩放控件
  });
};

onMounted(() => {
  obtainTempSetting();
  obtainTempData();
});
</script>

<style lang="scss" scoped></style>
